package com.xxx.mall.config;

import com.xxx.mall.exception.MallException;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 邢晨旭
 * {@code @date} 2023/11/20
 */
@Component
@Slf4j
public class MinioTemplate implements InitializingBean {

    @Resource
    private OssConfig ossConfig;

    private MinioClient minioClient;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.minioClient = MinioClient.builder().endpoint(ossConfig.getEndpoint())
                .credentials(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret())
                .build();
    }

    /**
     * 通过byte数组上传文件
     *
     * @param bytes
     * @param filePath
     * @param contentType
     * @throws IOException
     */
    public void uploadMinio(byte[] bytes, String filePath, String contentType) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = new ByteArrayInputStream(bytes);
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(ossConfig.getBucket())
                    .contentType(contentType)
                    .stream(inputStream, inputStream.available(), 0)
                    .object(filePath)
                    .build());
        } catch (Exception e) {
            log.error("上传文件失败", e);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /**
     * 获取预上传文件url
     *
     * @param objectName
     * @return
     */
    public String getPresignedObjectUrl(String objectName) {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(ossConfig.getBucket())
                    .object(objectName)
                    .expiry(10, TimeUnit.MINUTES)
                    .method(Method.PUT)
                    .build());
        } catch (Exception e) {
            log.error("获取文件url失败", e);
            throw new MallException("获取文件url失败");
        }
    }

    public void removeObject(String objectName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(ossConfig.getBucket())
                .object(objectName)
                .build());
    }

    public void removeObjects(List<String> objectNames) {
        minioClient.removeObjects(RemoveObjectsArgs.builder()
                .bucket(ossConfig.getBucket())
                .objects(objectNames.stream().map(DeleteObject::new).collect(Collectors.toList()))
                .build());
    }

}
